#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
detect_bulk.py

在 macOS 上扫描 ElectronBot 设备的所有接口和 altsetting，列出 Bulk IN/OUT 端点。
需要使用 sudo 权限执行。
"""
import usb.core, usb.util

def main():
    # 查找设备
    dev = usb.core.find(idVendor=0x1001, idProduct=0x8023)
    if dev is None:
        print("未找到 ElectronBot 设备 (VID=0x1001, PID=0x8023)")
        return

    # 卸载所有接口的内核驱动
    cfg = dev.get_active_configuration()
    for i in range(cfg.bNumInterfaces):
        try:
            if dev.is_kernel_driver_active(i):
                dev.detach_kernel_driver(i)
                print(f"[Info] 卸载内核驱动 Interface {i}")
        except Exception as e:
            print(f"[Warning] 卸载驱动 Interface {i} 失败: {e}")

    # 设置 Configuration
    try:
        dev.set_configuration()
    except Exception as e:
        print(f"[Error] set_configuration 失败: {e}")
        return

    cfg = dev.get_active_configuration()
    print("扫描所有 Interface & AltSetting：")
    for i in range(cfg.bNumInterfaces):
        # 获取当前接口所有 altsetting
        alts = [a.bAlternateSetting for a in cfg if a.bInterfaceNumber == i]
        num_alts = max(alts) + 1 if alts else 1
        for alt in range(num_alts):
            try:
                dev.set_interface_altsetting(interface=i, alternate_setting=alt)
                intf = cfg[(i, alt)]
                in_eps = [hex(ep.bEndpointAddress) for ep in intf
                          if usb.util.endpoint_direction(ep.bEndpointAddress) == usb.util.ENDPOINT_IN
                          and usb.util.endpoint_type(ep.bmAttributes) == usb.util.ENDPOINT_TYPE_BULK]
                out_eps = [hex(ep.bEndpointAddress) for ep in intf
                           if usb.util.endpoint_direction(ep.bEndpointAddress) == usb.util.ENDPOINT_OUT
                           and usb.util.endpoint_type(ep.bmAttributes) == usb.util.ENDPOINT_TYPE_BULK]
                if in_eps or out_eps:
                    print(f"  ✓ Interface={i} Alt={alt}  IN={in_eps}  OUT={out_eps}")
            except Exception as e:
                print(f"  Interface={i} Alt={alt} 失败: {e}")
    print("扫描完成。请根据以上结果，在 servo_test.py 中配置正确的接口和端点。")

if __name__ == '__main__':
    main()